package mvc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import java.io.*;
import java.util.*;


public class DBconn
{	
	//en connection class för att hålla reda på vår connection till databasen.
	Connection conn=null;

	//ett statement behövs för att ställa frågan till databasen.
	Statement stmnt=null;
	
	//ett resultset behövs för att hålla svaret vi får från databasen.
	ResultSet rs=null;
		
public DBconn(){}	
	
public ResultSet sqlQuery(String query){
	
	try {
		rs=stmnt.executeQuery(query);
	} catch (SQLException e) {
		rs=null;
		System.out.println("SQL Exception, sqlQuery");
		//e.printStackTrace(System.err);
	} 	
	return rs;
}	

public boolean sqlUpdate(String query){
	
	try {
		if(stmnt.executeUpdate(query)==1){
		return true;
		}
	} catch (SQLException e) {
		System.out.println("SQL Exception, sqlUpdate");
		//e.printStackTrace(System.err);
	}
	return false;
	
}

public void connect() throws IOException{
	/*
	Properties props = new Properties();
    FileInputStream in = new FileInputStream("database.properties");
    props.load(in);
    in.close();

    String driver = props.getProperty("jdbc.driver");
    String url = props.getProperty("jdbc.url");
    String username = props.getProperty("jdbc.username");
    String password = props.getProperty("jdbc.password");
	*/
	
	    String driver = "com.mysql.jdbc.Driver";
	    String url = "jdbc:mysql://localhost/mayClub";
	    String username = "user1";
	    String password = "pass1";
		
	try{
		Class.forName(driver);
		conn=DriverManager.getConnection(url,username,password);
		stmnt=conn.createStatement();						
	}
	catch(ClassNotFoundException cnfe){
		cnfe.printStackTrace(System.err);
	}
	catch(SQLException sql){
		sql.printStackTrace(System.err);
	}
}

public void closeConnection(){
	
	try{
		rs.close();
		stmnt.close();
		conn.close();
	}
	catch(Exception e){
		e.printStackTrace(System.err);
	}
}	

public String getString(String param){
	
	try{
		return rs.getString(param);
	}
	catch(SQLException e){
		//e.printStackTrace(System.err);
		return "null";
	}
}

public boolean next(){
	try {
		return rs.next();
	} catch (SQLException e) {
		e.printStackTrace(System.err);
		return false;
	}
	
}
	
/*
public static void main(String[] args) throws SQLException, IOException{
	
		DBconn a = new DBconn();
		a.connect();
		ResultSet hej=null;
		a.sqlQuery("SELECT firstname, lastname FROM person");
		
		while(a.next()){
			System.out.println("Name: " + a.getString("firstname") +" " + a.getString("lastname"));
		}
		
		if(a.sqlUpdate("delete from person where firstname = 'Robert'")){		
		a.sqlQuery("SELECT firstname, lastname FROM person");
		
		while(a.next()){
			System.out.println("Name: " + a.getString("firstname") +" " + a.getString("lastname"));
		}
	}
		
}
*/


}

